from django import forms
from django.core.exceptions import ValidationError
from web.forms.bootstrap import BootStrapForm
from web import models
from web.forms.widgets import ColorRadioSelect


class ProjectModelForm(BootStrapForm, forms.ModelForm):
    bootstrap_class_exclude = ['color']
    # 重写 description字段 attrs 添加属性
    # 方法一
    # description = forms.CharField(widget=forms.Textarea(attrs={'xx':'yy'}))

    class Meta:
        model = models.Project
        fields = ['name', 'color', 'description']
        widgets = {
            'description': forms.Textarea,  # 方法二 重写 description字段
            'color': ColorRadioSelect(attrs={'class':'color-radio'}),
        }

    def __init__(self,request,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.request = request

    def clean_name(self):
        name = self.cleaned_data['name']
        creator = self.request.tracer.user

        # 查询项目名（对应的创建人）是否存在
        exists = models.Project.objects.filter(name=name,creator=creator).exists()
        if exists:
            raise ValidationError('项目已存在，请重新创建')

        # 当前创建的项目个数
        count = models.Project.objects.filter(creator=creator).count()
        if count >= self.request.tracer.price_policy.project_num:
            raise ValidationError('项目个数超限，请重新购买套餐')
        return name
